package com.xhwl.logistics.strategy.impl;

import com.xhwl.logistics.bo.VehicleCarChargeInfoBO;
import com.xhwl.logistics.bo.cent.VehicleIntegratedConfigBO;
import com.xhwl.logistics.bo.input.QueryVehicleCarChargeBO;
import com.xhwl.logistics.converter.mapstruct.VehicleCarChargeConverter;
import com.xhwl.logistics.dto.http.CarChargeKeTopDTO;
import com.xhwl.logistics.dto.http.ChargeInfoKeTopDTO;
import com.xhwl.logistics.dto.http.query.QueryCarChargeKeTopDTO;
import com.xhwl.logistics.enums.VehicleCardTypeEnum;
import com.xhwl.logistics.service.impl.http.KeTopHttpServiceImpl;
import com.xhwl.logistics.strategy.IVehicleParkingLotCarChargeHandler;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//@Service
public class VehicleParkingLotKeTopCarChargeHandlerImpl implements IVehicleParkingLotCarChargeHandler {

    @Autowired
    private KeTopHttpServiceImpl keTopHttpService;

    @Autowired
    private VehicleCarChargeConverter vehicleCarChargeConverter;

    @Override
    public List<VehicleCarChargeInfoBO> carCharge(VehicleIntegratedConfigBO vehicleIntegratedConfigBO, QueryVehicleCarChargeBO queryVehicleCarChargeBO) {
        QueryCarChargeKeTopDTO queryCarChargeKeTopDTO = vehicleCarChargeConverter.queryVehicleCarChargeBO2QueryCarChargeKeTopDTO(queryVehicleCarChargeBO);

        CarChargeKeTopDTO carChargeKeTopDTO = keTopHttpService.queryCarCharge(vehicleIntegratedConfigBO, queryCarChargeKeTopDTO);

        Integer pageSize = queryCarChargeKeTopDTO.getPageSize();
        Integer totalCount = carChargeKeTopDTO.getTotalCount();
        int count = totalCount / pageSize;

        List<CarChargeKeTopDTO> carChargeKeTopDTOList = new ArrayList<>();
        carChargeKeTopDTOList.add(carChargeKeTopDTO);
        for (int i = 0; i < count; i++) {
            int initPageIndex = 2;

            QueryCarChargeKeTopDTO pageQuery = vehicleCarChargeConverter.queryVehicleCarChargeBO2QueryCarChargeKeTopDTO(queryVehicleCarChargeBO);
            pageQuery.setPageIndex(initPageIndex + i);

            CarChargeKeTopDTO pageResult = keTopHttpService.queryCarCharge(vehicleIntegratedConfigBO, pageQuery);
            carChargeKeTopDTOList.add(pageResult);
        }

        List<VehicleCarChargeInfoBO> vehicleCarChargeInfoBOList = new ArrayList<>();
        Map<Integer, Integer> map = carChargeKeTopDTOList.stream()
                .flatMap(carCharge -> carCharge.getChargeList().stream())
                .collect(Collectors.groupingBy(ChargeInfoKeTopDTO::getCarType, Collectors.summingInt(ChargeInfoKeTopDTO::getAmount)));

        map.forEach((key, value) -> {
            String cardType = VehicleCardTypeEnum.toVehicleCardTypeEnumByKeTop(key).getCode();
            int pay = value / 100;
            vehicleCarChargeInfoBOList.add(new VehicleCarChargeInfoBO(cardType, pay));
        });

        return vehicleCarChargeInfoBOList;
    }
}
